#include <stdio.h>
#include <sys/socket.h>
#include <errno.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <getopt.h>

void printf_help(char *progname )
{
	printf("%s usage:\n",progname);
	printf("-i(--ipaddr):sepcify server ip address\n");
	printf("-p(--port):sepcify server port\n");
	printf("-h(--help):print this help information\n");
}

int main(int argc,char **argv)
{

	int                   con_fd=-1;
	struct   sockaddr_in  serv_addr;
	int                       rv=-1;
	char             *servip= NULL ;
	int                  servport=0;
	char                  buf[128];
	int                 *index=NULL;
	int                          ch;
	char                  *set=NULL;

	struct  option  opts[]={
	
		{"ipaddr",required_argument,NULL,'i'},
		{"port",required_argument,NULL,'p'},
		{"help",no_argument,NULL,'h'},
		{"set",required_argument,NULL,'s'},
		{0,0,0,0}
	};



	while( (ch=getopt_long(argc,argv,"i:p:s:h",opts,index)) != -1  )
	{
		switch(ch)
		{
			case'i':
				servip=optarg;
				break;
			case'p':
				servport=atoi(optarg);
				break;
			case'h':
				printf_help(argv[0]);
				return 0;
			case's':
				set=optarg;
				break;                    //为什么要用break？
		}
	}
	printf("set:%s\n",set);
	if(!servip || !servport  )
	{
		printf_help(argv[0]);
		return -1;
	
	}

	con_fd=socket(AF_INET,SOCK_STREAM,0);
	if(con_fd<0)
	{
		printf("create socket falure:%s\n",strerror(errno));
		return -1;
	}
	printf("create socket [%d] successfully!\n",con_fd);

	//定义服务器协议以及地址，端口
	memset(&serv_addr,0,sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	//客户端要找到该服务器，需要知道该服务器的IP、端口，并发到Internet上访问查找是否有该服务器，则需将本机字节序转换成网络字节序
	serv_addr.sin_port  = htons(servport);//htons：将主机字节序转换成网络字节序
	inet_aton(servip,&serv_addr.sin_addr);//inet_aton:将点分十进制ip字符串转换成整形的网络字节序
	printf("serv_addr.sin_port:[%d] net_int\n",serv_addr.sin_port);//查看端口网络字节序
	printf("serv_addr.sin_addr:[%d] net_int\n",serv_addr.sin_addr.s_addr);//查看IP网络字节序
	printf("serv_addr.sin_addr:[%d] host_int\n",ntohl(serv_addr.sin_addr.s_addr));//查看IP网络字节序


	rv=connect(con_fd,(struct sockaddr *)&serv_addr,sizeof(serv_addr));
	
	if(rv<0)
	{
		printf("connect [%d] falure:%s\n",con_fd,strerror(errno));
		return -2;
	}
	printf("connect server:[IP:%s;PORT:%d] successfully\n",
			inet_ntoa(serv_addr.sin_addr),ntohs(serv_addr.sin_port));

	while(1)	
	{
		rv=write(con_fd,set,strlen(set));
		if(rv<0)
		{
			printf("write to server falure:%s\n",strerror(errno));
			break;
		}
		printf("write '%s' data %d byte to server successfully\n",set,rv);
	
		memset(buf,0,sizeof(buf));
		rv=read(con_fd,buf,sizeof(buf));
		if(rv<0)
		{
			printf("read falure:%s\n",strerror(errno));
			break;
		}
		else if(rv==0)		
		{
			printf("connect server break\n");
			break;
		}
		printf("read data %d byte:%s\n",rv,buf);
	} 

	close(con_fd);
	return 0;
}

